package utils

import (
	"bytes"
	"dingbot/config"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func GenerateImages(prompts string) ([][]byte, error) {
	// 获取配置实例
	conf := config.GetConfig()
	negativePrompt := "nsfw,logo,text,EasyNegative,negative_hand-neg,mutated hands and fingers,poorly drawn face,extra limb,missing limb,disconnected limbs,malformed hands,ugly,"
	prompt := "best quality,masterpiece," + prompts
	width := 800
	height := 1000
	// 构造要发送的 JSON 数据
	jsonData := struct {
		Prompt         string `json:"prompt"`
		NegativePrompt string `json:"negative_prompt"`
		Width          int    `json:"width"`
		Height         int    `json:"height"`
	}{
		Prompt:         prompt,
		NegativePrompt: negativePrompt,
		Width:          width,
		Height:         height,
	}

	// 将结构体转换为 JSON 格式
	requestBody, err := json.Marshal(jsonData)
	if err != nil {
		return nil, fmt.Errorf("error encoding JSON: %v", err)
	}

	// 构造 HTTP 请求
	req, err := http.NewRequest("POST", conf.API.ImgUrl, bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, fmt.Errorf("error creating request: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")

	// 发送请求并获取响应
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("error response status: %s", resp.Status)
	}

	// 读取响应体
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response body: %v", err)
	}

	// 解析 JSON 响应
	var data map[string]interface{}
	if err := json.Unmarshal(responseBody, &data); err != nil {
		return nil, fmt.Errorf("error parsing JSON: %v", err)
	}

	// 获取 images 字段的值
	images, ok := data["images"].([]interface{})
	if !ok {
		return nil, fmt.Errorf("error getting images data")
	}

	// 遍历 images 数组，并解码图片数据
	var decodedImages [][]byte
	for _, image := range images {
		imageData, ok := image.(string)
		if !ok {
			continue
		}
		// 解码 Base64 编码的图片数据
		decodedData, err := base64.StdEncoding.DecodeString(imageData)
		if err != nil {
			continue
		}
		decodedImages = append(decodedImages, decodedData)
	}
	return decodedImages, nil
}

//func sd() {
//	// 用户设置的 prompt
//	prompts := "A dog sleeps lying on the grass"
//
//	// 调用 generateImages 函数，获取图片数据
//	images, err := generateImages(prompts)
//	if err != nil {
//		fmt.Println("Error generating images:", err)
//		return
//	}
//
//	// 保存图片数据到文件
//	for i, imageData := range images {
//		err := ioutil.WriteFile(fmt.Sprintf("image%d.jpg", i+1), imageData, 0644)
//		if err != nil {
//			fmt.Println("Error saving image data to file:", err)
//			continue
//		}
//		fmt.Println("Image", i+1, "saved successfully")
//	}
//}
